package top.eggcode.system.modules.user.store;

import org.springframework.stereotype.Repository;
import top.eggcode.common.base.JpaSimpleStore;
import top.eggcode.common.model.ListPage;
import top.eggcode.plugins.query.CriteriaBuilder;
import top.eggcode.system.modules.user.model.UserBiz;
import top.eggcode.system.modules.user.model.UserEntity;
import top.eggcode.system.modules.user.model.UserQuery;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import java.util.Optional;

/**
 * Title:
 * Description: TODO
 * Date: 2021/5/8 14:10
 *
 * @author JiaQi Ding
 * @version 1.0
 */
@Repository
public class UserStore extends JpaSimpleStore<UserEntity, String> {

    @Resource
    private CriteriaBuilder builder;

    public UserStore(EntityManager manager) {
        super(UserEntity.class, manager);
    }

    public Optional<UserEntity> queryOne(String id) {
        return Optional.of(manager.find(UserEntity.class, id));
    }

    public ListPage<UserBiz> page(UserQuery query) {
        return builder.createQuery(UserBiz.class)
                .select("root.username, root.id as account_id, u.*")
                .from("auth_account", "root")
                .leftJoin("system_user", "u", "root.user_id = u.id")
                .where(condition -> {
                    if (query.getNickname() != null) {
                        condition.likeAny("u.nickname", query.getNickname());
                    }
                    if (query.getSex() != null) {
                        condition.eq("u.sex", query.getSex());
                    }
                    if (query.getUsername() != null) {
                        condition.likeAny("root.username", query.getUsername());
                    }
                })
                .fetchPage(query);
    }
}
